package com.zmzncs.lmtc.module.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmzncs.lmtc.common.pojo.PageInfo;
import com.zmzncs.lmtc.common.pojo.Rest;
import com.zmzncs.lmtc.common.util.JsonUtil;
import com.zmzncs.lmtc.common.util.JwtUtil;
import com.zmzncs.lmtc.common.util.MD5Util;
import com.zmzncs.lmtc.common.util.RestUtil;
import com.zmzncs.lmtc.module.system.dao.UserMapper;
import com.zmzncs.lmtc.module.system.pojo.role_permission.RolePermissionDTO;
import com.zmzncs.lmtc.module.system.pojo.user.*;
import com.zmzncs.lmtc.module.system.service.RolePermissionService;
import com.zmzncs.lmtc.module.system.service.UserService;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 人员 前端控制器
 * </p>
 *
 * @author 任建波
 * @since 2019-08-09
 */
@Api(value = "人员",tags = "人员")
@RestController
@RequestMapping("/system/user")
@Validated
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    HttpServletRequest request;
    @Autowired
    RolePermissionService rolePermissionService;

    @ApiOperation(value = "登录")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="query", name = "account", value = "账户",  required = true),
        @ApiImplicitParam(paramType="query", name = "password", value = "密码",  required = true)
    })
    @PostMapping(value = "login")
    public Rest<UserLoginVO> login(String account, String password) {
        if(StringUtils.isBlank(account) || StringUtils.isBlank(password)){
            return RestUtil.warning(401, "账号和密码不能为空");
        }
        UserDTO userDTO = userMapper.getByAccount(account);
        if (userDTO == null){
            return RestUtil.warning( "账号或密码不正确");
        }
        //  末尾随机数字位数
        String randomCount = password.substring(password.length() - 1);
        Boolean isNumber = randomCount.matches("[0-9]+");
        if(isNumber == false){
            return RestUtil.warning( "账号或密码不正确");
        }
        //  有效密码长度（form密码长度 - 无效字符长度）
        int passwordLength = password.length() - Integer.parseInt(randomCount) - 1;
        //  随机数
        String random = password.substring(passwordLength, password.length() - 1);
        String formPassword = password.substring(0, passwordLength);
        String encryptionPassword = MD5Util.md5(userDTO.getPassword() + random);
        log.info("随机数：{}，请求加密密码：{}，数据库密码：{}，根据随机数加密数据库密码：{}", random, formPassword, userDTO.getPassword(), encryptionPassword);

        if (!formPassword.equals(encryptionPassword)){
            return RestUtil.warning( "账号或密码不正确");
        }else {
            //  根据角色id查询角色权限数组
            List<RolePermissionDTO> rolePermissionDTOList = rolePermissionService.getRolePermissionListByRoleId(userDTO.getRoleId());
            if(rolePermissionDTOList .size() == 0 && !userDTO.getRoleId().equals(1)){
                return RestUtil.warning("你的账号还没有分配权限，请联系管理员");
            } else {
                UserLoginVO userLoginVO = new UserLoginVO();
                userLoginVO.setUserId(userDTO.getId());
                BeanUtils.copyProperties(userDTO, userLoginVO);
                List<Long> permissionIdList = rolePermissionDTOList.stream().map(RolePermissionDTO::getPermissionId).collect(Collectors.toList());
                List<String> permissionCodeList = rolePermissionDTOList.stream().map(RolePermissionDTO::getPermissionCode).collect(Collectors.toList());
                userLoginVO.setPermissionIdList(permissionIdList);
                userLoginVO.setPermissionCodeList(permissionCodeList);
                userLoginVO.setToken(JwtUtil.createJWT(userLoginVO));

                return RestUtil.success(userLoginVO);
            }
        }
    }

    @ApiOperation(value = "退出")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "header", name = "token", value = "请求头token", required = true, dataType = "String"),
    })
    @PostMapping(value = "logout")
    public Rest logout() {
        return RestUtil.success();
    }

    @ApiOperation(value = "获取用户分页列表")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "header", name = "token", value = "请求头token", required = true),
        @ApiImplicitParam(name = "currentPage", value = "页码", required = true),
        @ApiImplicitParam(name = "size", value = "每页条数", required = true),
        @ApiImplicitParam(name = "keyword", value = "姓名或账号查询")
    })
    @GetMapping(value = "page")
    public Rest<PageInfo<UserVO>> page(UserSearchFrom form) {
        IPage<UserDTO> iPage = userService.getUserList(form);
        PageInfo<UserVO> pageInfo = JsonUtil.pageTransform(iPage, UserVO.class);

        return RestUtil.success(pageInfo);
    }

    @ApiOperation(value = "获取登录人员")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "header", name = "token", value = "请求头token", required = true, dataType = "String"),
    })
    @RequestMapping(value = "getLoginUserInfo", method = RequestMethod.GET)
    public Rest<UserInfoVO> getLoginUserInfo(){
        UserLoginVO loginUser = JwtUtil.getLoginUser(request);

        User user = userService.getById(loginUser.getUserId());
        List<RolePermissionDTO> rolePermissionDTOList = rolePermissionService.getRolePermissionListByRoleId(loginUser.getRoleId());

        Long[] permissionIds = new Long[rolePermissionDTOList.size()];
        String[] permissionCodes = new String[rolePermissionDTOList.size()];
        for(int i=0; i< rolePermissionDTOList.size(); i++){
            permissionIds[i] = rolePermissionDTOList.get(i).getPermissionId();
            permissionCodes[i] = rolePermissionDTOList.get(i).getPermissionCode();
        }

        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(user, userInfoVO);

        userInfoVO.setPermissionIds(permissionIds);
        userInfoVO.setPermissionCodes(permissionCodes);
        userInfoVO.setAvatar("http://f.hiphotos.baidu.com/image/h%3D300/sign=d985fb87d81b0ef473e89e5eedc551a1/b151f8198618367aa7f3cc7424738bd4b31ce525.jpg");
        return RestUtil.success(userInfoVO);
    }

    @ApiOperation(value = "根据id获取人员")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "header", name = "token", value = "请求头token", required = true, dataType = "String"),
    })
    @RequestMapping(value = "getUserById", method = RequestMethod.GET)
    public Rest<UserInfoVO> getUserById(Integer id){
        User user = userService.getById(id);
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(user,userInfoVO);

        user.setAvatar("http://f.hiphotos.baidu.com/image/h%3D300/sign=d985fb87d81b0ef473e89e5eedc551a1/b151f8198618367aa7f3cc7424738bd4b31ce525.jpg");
        return RestUtil.success(userInfoVO);
    }

    @ApiOperation(value = "添加人员")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "header", name = "token", value = "请求头token", required = true, dataType = "String"),
    })
    @RequestMapping(value = "addUser", method = RequestMethod.POST)
    @Transactional
    public Rest addUser(@Valid UserAddFrom userAddFrom){
        User user = new User();
        BeanUtils.copyProperties(userAddFrom, user);
        user.setPassword(MD5Util.generatePassword("123456"));
        userService.save(user);

        return RestUtil.success();
    }

    @ApiOperation(value = "修改人员")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "header", name = "token", value = "请求头token", required = true, dataType = "String"),
    })
    @RequestMapping(value = "updateUser", method = RequestMethod.POST)
    public Rest updateUser(@Valid UserUpdateFrom userUpdateFrom){
        Claims claims = JwtUtil.parseJWT(request);
        Integer userId = claims.get("userId", Integer.class);

        User user = new User();
        BeanUtils.copyProperties(userUpdateFrom, user);
        userService.updateById(user);

        return RestUtil.success();
    }

    @ApiOperation(value = "删除人员")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "header", name = "token", value = "请求头token", required = true, dataType = "String"),
    })
    @PostMapping(value = "deleteUser")
    public Rest deleteUser(@NotNull Long id){
        User user = new User();
        user.setId(id);
        user.setIsDeleted(1);
        userService.updateById(user);

        return RestUtil.success();
    }

    @ApiOperation(value = "重置密码")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "header", name = "token", value = "请求头token", required = true, dataType = "String"),
    })
    @PostMapping(value = "resetPassword")
    public Rest resetPassword(@NotNull Long userId, @NotBlank String password){
        User user = new User();
        user.setId(userId);
        user.setPassword(MD5Util.generatePassword(password));
        userService.updateById(user);

        return RestUtil.success();
    }

    @ApiOperation(value = "修改密码")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "header", name = "token", value = "请求头token", required = true, dataType = "String"),
    })
    @PostMapping(value = "updatePassword")
    public Rest updatePassword(@NotNull Long userId, @NotBlank String currentPassword, @NotBlank String newPassword){
         QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", userId);
        queryWrapper.eq("password", MD5Util.generatePassword(currentPassword));
        queryWrapper.eq("is_deleted", 0);
        User user = userService.getOne(queryWrapper);
        if(user == null){
            return RestUtil.warning("当前密码输入不正确");
        } else {
            user.setId(userId);
            user.setPassword(MD5Util.generatePassword(newPassword));
            userService.updateById(user);

            return RestUtil.success();
        }
    }

}

